﻿#!/usr/bin/python
# -*- coding: UTF-8 -*-
from optparse import OptionParser
from printLog import printLog
import jsonFileUtils
import deleteUnusedMetaFile
import os
import shutil

enginePath = 'C:/CocosCreator_2.2.1'
COCOS_BUILD_CMD = 'CocosCreator.exe --path {0} --build \"{1}\"'
COCOS_COMPILE_CMD = 'CocosCreator.exe --path {0} --compile \"{1}\"'
BUILD_PARAM = 'platform=android;debug=false;appABIs=[\'armeabi-v7a\'];optimizeHotUpdate=false;inlineSpriteFrames=false;mergeStartScene=true;template=link;apiLevel=android-29;\
androidStudio=true;xxteaKey=1449bb9d-2f98-4f;zipCompressJs=true;encryptJs=true;\
useDebugKeystore=false;keystorePassword=liangzi;keystoreAlias=liangzi;keystoreAliasPassword=liangzi;md5Cache=false;'


KEY_STORE_PATH = 'liangzi_release.jks'
# cocos BUILDER
COCOS_BUILDER_PATH = 'settings/builder.json'
START_SCENE_UUID = '5dffaf13-b2fe-4cde-aa78-dbe84c726374'


def getBuildCMD(workSpace, buildParam):
    return COCOS_BUILD_CMD.format(workSpace, buildParam)


def addBuildParam(buildParam, param):
    buildParam += ';' + param
    return buildParam

def excuteCmd(cmdStr):
    os.system(cmdStr)

def updateStartSceneUuid():
    data = jsonFileUtils.getJsonDataFromFile(COCOS_BUILDER_PATH)
    data['startScene'] = START_SCENE_UUID
    jsonFileUtils.saveJsonDataToFile(COCOS_BUILDER_PATH, data)

def getAndroidBuildParam(workSpace):
    buildParam = BUILD_PARAM
    keyStorePath = os.path.abspath(os.path.join(workSpace, KEY_STORE_PATH))
    buildParam = addBuildParam(buildParam, 'keystorePath=' + keyStorePath)
    return buildParam


def setDebugCompileParam():
    netType = os.environ['NETTYPE']
    if netType == 'innertest':
        global BUILD_PARAM
        BUILD_PARAM = BUILD_PARAM.replace('debug=false', 'debug=true')
        print('inner_test_param =', BUILD_PARAM)


def buildAndroid(workSpace):
    deleteUnusedMetaFile.run()
    setDebugCompileParam()
    buildParam = getAndroidBuildParam(workSpace)
    cwd = os.getcwd()
    os.chdir(enginePath)
    cmdBuild = getBuildCMD(workSpace, buildParam)
    excuteCmd(cmdBuild)
    os.chdir(cwd)



if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option(
        '-e', '--enginePath', dest="enginePath", default='C:/CocosCreator_2.2.1')
    parser.add_option('-w', '--workSpace', dest="workSpace", default='../')
    (option, args) = parser.parse_args()
    enginePath = option.enginePath
    workSpace = os.path.abspath(os.path.join(os.getcwd(), option.workSpace))
    os.chdir(workSpace)
    printLog("-------------引擎目录-----------" + enginePath)
    printLog("-------------工作目录-----------" + workSpace)
    updateStartSceneUuid()
    buildAndroid(workSpace)